//
//  YWDoEquipmentInspectionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/11.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoEquipmentInspectionTableViewController.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWInspectionMissionModel.h"

#import "YWPostTroubleInfoCell.h"
#import "YWRuleTableViewCell.h"
#import "YWSaveButtonCell.h"
#import "YWTakePhotoCell.h"
#import "YWWriteNoteCell.h"
#import "YWWriteRuntimeCell.h"
#import "YWDropDownRunTimeCell.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"

#import "YWShowPostTroubleInfoTableViewController.h"
#import "YWPostTroubleTableViewController.h"

#import "YWKeepWatchMissionManager.h"
#import "YWMissionManager.h"
#import "YWDictEquipmentRule.h"
#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWInspectionEquipmentRecord.h"
#import "YWInspectionMissionManager.h"
#import "YWMacro.h"
#import "YWMissionRuleResult.h"
#import "YWEquipmentType.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWEquipmentFieldRecord.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"

@interface YWDoEquipmentInspectionTableViewController () <YWTakePhotoCellDelegate, YWSaveButtonCellDelegate>
//选中的设备
@property (nonatomic, strong) YWEquipment* currentEquipment;
//规则
@property (nonatomic, strong) NSMutableArray* missionRuleResults;
//规则内容
@property (nonatomic, strong) NSString* missionRuleContent;

@property (nonatomic, strong) UIView* footView;
@property (nonatomic, strong) UIButton* myTroublesButton;
@property (nonatomic, strong) UIButton* finishedButton;

//@property (nonatomic, strong) NSArray* allEquipments;
//@property (nonatomic, strong) NSMutableArray* recordEquipmentIds;
//@property (nonatomic, strong) NSMutableArray* missionEquipmntIds;

@property (nonatomic, weak) MBProgressHUD* HUD;
//点击保存按钮的设备
//@property (nonatomic, strong) NSMutableArray *saveEquipmentArray;

//报障设备记录数组
//@property (nonatomic, strong) NSMutableArray *postTroubleRecordArray;
@end

@implementation YWDoEquipmentInspectionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"inspection", nil);//@"巡查";
    
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    [self.tableView registerClass:[YWWriteRuntimeCell class] forCellReuseIdentifier:YWWriteRuntimeCellIdentifier];
    [self.tableView registerClass:[YWDropDownRunTimeCell class] forCellReuseIdentifier:YWDropDownRunTimeCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWSaveButtonCell class] forCellReuseIdentifier:YWSaveButtonCellIdentifier];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showTipsWhenFirstEnter];
    });
    
    //测试很多点一起提交的情况
//    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:_inspectionMission];
//    YWInspectionLineRecord *record = [[YWInspectionLineRecord alloc]init];
//    record.inspectionLineId = _inspectionMission.inspectionLine.inspectionLineId;
//    record.uniqueTag = uniqueTag;
//    record.count = 0;
//    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970]*1000;
//    record.startTime = nowTime;
//    record.endTime = nowTime;
//    record.result = YWInspectionLineRecordResultUnfinishAndNormal;
//    YWLoginUser *currentUser = [YWLoginTool loginUser];
//    record.executorIds = [NSString stringWithFormat:@"%ld",(long)currentUser.uniqueId];
//    record.inspectionMissionId = _inspectionMission.inspectionMissionId;
//    
//    NSArray* totalPoint = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:record.inspectionLineId];
//    _saveEquipmentArray = [NSMutableArray array];
//    for (YWEquipment *equipment in totalPoint) {
//        [_saveEquipmentArray addObject:equipment];
//        //if (_saveEquipmentArray.count == 100) {
//            //break;
//        //}
//    }
//    NSArray* recordArray = [self createEquipmentRecord:record];
//    //[[YWInspectionMissionManager shareManager] startUploadInspectionRecords:recordArray pictures:nil WithType:YWInspectionEquipmentRecordTypeEquipment];
//    [[YWInspectionMissionManager shareManager] updateInspectionEquipmentRecordWithArray:recordArray];
}

//- (NSMutableArray*)recordEquipmentIds{
//    if (!_recordEquipmentIds) {
//        _recordEquipmentIds = [NSMutableArray array];
//        NSString* uniqueTag = [YWCommonTool uniqueTagWithMission:_inspectionMission];
//        YWInspectionLineRecord* record = [[YWInspectionMissionManager shareManager] latestInspectionLineRecordUniqueTag:uniqueTag];
//        if (record) {
//            NSArray* finishEquipmentRecords = [[YWInspectionMissionManager shareManager] inspectionEquipmentRecordWithUniqueTag:record.uniqueTag];
//            [finishEquipmentRecords enumerateObjectsUsingBlock:^(YWInspectionEquipmentRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
//                if (record.equipment.equipmentId) {
//                    [_recordEquipmentIds addObject:record.equipment.equipmentId];
//                }
//            }];
//        }
//    }
//    return _recordEquipmentIds;
//}

//- (NSMutableArray *)saveEquipmentArray{
//    if (!_saveEquipmentArray) {
//        _saveEquipmentArray = [NSMutableArray array];
//    }
//    return _saveEquipmentArray;
//}

//- (NSMutableArray*)missionEquipmntIds
//{
//    if (!_missionEquipmntIds) {
//        _missionEquipmntIds = [NSMutableArray array];
//    }
//    return _missionEquipmntIds;
//}

//- (void)setInspectionMission:(YWInspectionMissionModel*)inspectionMission
//{
//    _inspectionMission = inspectionMission;
//    _allEquipments = nil;
//    if (_qrcodeID) {
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrcodeID];
//    }else if (_locationId){
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
//    }
//    
//    NSArray* missionEquipments = _inspectionMission.inspectionLine.equipments;
//    if (missionEquipments.count == 0) {
//        missionEquipments = [[YWInspectionMissionManager shareManager] allInspectionEquipmentWithLineId:self.inspectionMission.inspectionLine.inspectionLineId];
//    }
//    
//    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
//        [missionEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull missionEqu, NSUInteger idx, BOOL * _Nonnull equStop) {
//            if ([missionEqu.equipmentId isEqualToString:equipment.equipmentId] && ![self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                if (_currentEquipment == nil) {
//                    _currentEquipment = equipment;
//                }
//                if (equipment.equipmentId) {
//                    [self.missionEquipmntIds addObject:equipment.equipmentId];
//                    //自动保存要做的设备
//                    [self.saveEquipmentArray addObject:equipment];
//                }
//            }
//        }];
//        NSArray* runTimeParameterArray = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:YWMaintenanceTypePatrol];
//        equipment.runTimeParameterArray = runTimeParameterArray.count ? runTimeParameterArray : nil;
//    }];
//}

- (void)setAllEquipments:(NSArray *)allEquipments{
    _allEquipments = allEquipments;
    _currentEquipment = _allEquipments[0];
}

- (NSMutableArray*)missionRuleResults{
    if (!_missionRuleResults) {
        NSMutableArray* missionRuleResults = [[NSMutableArray alloc] init];
        NSArray* equipmentRules = [[YWEquipmentManager shareManager] rulesWithEquipmentTypeId:_currentEquipment.equipmentTypeId maintenanceTypeId:YWMaintenanceTypePatrol maintenanceCycleId:YWMissionCycleNull];

        [equipmentRules enumerateObjectsUsingBlock:^(YWDictEquipmentRule* _Nonnull rule, NSUInteger idx, BOOL* _Nonnull stop) {
            YWMissionRuleResult* missionRuleResult = [[YWMissionRuleResult alloc] init];
            missionRuleResult.content = rule.content;
            [missionRuleResults addObject:missionRuleResult];
        }];
        _missionRuleResults = missionRuleResults;
    }
    return _missionRuleResults;
}

- (NSString*)missionRuleContent{
    if (!_missionRuleContent) {
        NSString* string = nil;
        NSArray *ruleArray = self.missionRuleResults;
        BOOL haveRule = ruleArray.count > 0 ? YES : NO;
        NSMutableString* ruleContent = [NSMutableString string];

        for (int i = 0; i < (haveRule ? ruleArray.count : 1); i++) {
            if (haveRule) {
                YWMissionRuleResult* missionRuleResult = ruleArray[i];
                string = [NSString stringWithFormat:@"%d.%@", i + 1, missionRuleResult.content];
            }
            else {
                string = NSLocalizedString(@"none", nil);
            }
            if (i != 0) {
                [ruleContent appendString:@"\n"];
            }
            [ruleContent appendString:string];
        }
        _missionRuleContent = [NSString stringWithFormat:@"%@", ruleContent];
    }
    return _missionRuleContent;
}

- (UIView*)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        //      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
        //      完成
        _finishedButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _finishedButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _finishedButton.layer.masksToBounds = YES;
        _finishedButton.layer.cornerRadius = 5.0;
        
        [_finishedButton setTitle:NSLocalizedString(@"finish", nil) forState:UIControlStateNormal];
        [_finishedButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _finishedButton.backgroundColor = [UIColor customBlueColor];
        [_finishedButton addTarget:self action:@selector(clickFinishButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_finishedButton];
        
    }
    return _footView;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        //选择设备
        return UITableViewAutomaticDimension;//44;
    }else if (indexPath.section == 1) {
        //规则
        return UITableViewAutomaticDimension;//[YWRuleTableViewCell cellHeightOfRuleContent:self.missionRuleContent];
    }else if (indexPath.section == 2) {
        //运行参数
        return _currentEquipment.runTimeParameterArray.count ? 75 : 44;
    }else if (indexPath.section == 3) {
        //备注
        return 90;
    }else{
        //拍照(高度是动态变化的)
        if (indexPath.row == 0) {
            CGFloat imageH = YWPhotoSize*(_currentEquipment.totalImageNameArray.count/4+1) + YWPhotoGap*(_currentEquipment.totalImageNameArray.count/4);
            return 10*2 + imageH;
        }else{
            return UITableViewAutomaticDimension;//44;
        }
    }
//    else {
//        //报障设备
//        return _postTroubleRecordArray.count>0 ? 54 : 44;
//    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 5;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _allEquipments.count;
    }else if (section == 2) {
        return _currentEquipment.runTimeParameterArray.count ?: 1;
    }else if (section == 4) {
        return 2;
    }else{
        return 1;
    }
    //else if (section == 5) {
//    return _postTroubleRecordArray.count ?: 1;
//}
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        static NSString* identifier = @"YWDoEquipmentInspectionTableViewControllerIdentifier";
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        YWEquipment* equipment = self.allEquipments[indexPath.row];
        cell.textLabel.text = equipment.equipmentName ?: @"";
        cell.detailTextLabel.text = [self.saveEquipmentArray containsObject:equipment] ? @"已保存" : nil;
        if ([equipment.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
//        if ([self.missionEquipmntIds containsObject:equipment.equipmentId]) {
//            if ([self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                cell.textLabel.textColor = [UIColor customTextGrayColor];
//            }else {
//                cell.textLabel.textColor = [UIColor blackColor];
//            }
//        }else {
//            cell.textLabel.textColor = [UIColor customTextGrayColor];
//        }
        return cell;
    }
    else if (indexPath.section == 1) {

        YWRuleTableViewCell* cell = [YWRuleTableViewCell cellWithTableView:tableView];
        cell.ruleContent = self.missionRuleContent;
        return cell;
    }
    else if (indexPath.section == 2) {
        YWRunTimeParameter *runTimeParameter = _currentEquipment.runTimeParameterArray.count ? _currentEquipment.runTimeParameterArray[indexPath.row]:nil;
        if (runTimeParameter.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
            YWDropDownRunTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDropDownRunTimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }else{
            YWWriteRuntimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteRuntimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }
    }
    else if (indexPath.section == 3) {
        YWWriteNoteCell* cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.equipment = _currentEquipment;
        return cell;
    }else{//if (indexPath.section == 4)
        if (indexPath.row==0) {
            YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
            cell.totalImageNameArray = _currentEquipment.totalImageNameArray;
            cell.delegate = self;
            return cell;
        }else{
            YWSaveButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:YWSaveButtonCellIdentifier];
            cell.delegate = self;
            cell.isSave = [self.saveEquipmentArray containsObject:_currentEquipment] ? YES :NO;
            return cell;
        }
    }
//    else {
//        YWPostTroubleInfoCell* cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
//        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count > 0 ? _postTroubleRecordArray[indexPath.row] : nil;
//        cell.reportTrouble = reportTrouble;
//        return cell;
//    }
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        YWEquipment* equipment = self.allEquipments[indexPath.row];
//        if ([self.missionEquipmntIds containsObject:equipment.equipmentId]) {
//            if ([self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                [YWCommonTool showTextHUDWithContent:@"该设备已完成"];
//            }else {
                if (_currentEquipment && _currentEquipment.equipmentTypeId != equipment.equipmentTypeId) {
                    self.missionRuleContent = nil;
                    self.missionRuleResults = nil;
                }
                _currentEquipment = equipment;
//            }
//        }else {
//            [YWCommonTool showTextHUDWithContent:@"不是该任务的设备"];
//        }
        [self.tableView reloadData];
    }
//    else if (indexPath.section == 5){
//        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
//        if (reportTrouble) {
//            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
//            showPostTroubleVC.reportTrouble = reportTrouble;
//            showPostTroubleVC.delegate = self;
//            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
//        }
//    }
}

#pragma mark - tableView.headerView

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWDoEquipmentInspectionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString* headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString*)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else if (section==1){
        return NSLocalizedString(@"inspectionItem", nil);//@"巡查项";
    }else if (section==2){
        return NSLocalizedString(@"runtimeParameter", nil);//@"运行参数";
    }else if (section==3){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else{
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
//    else{
//        return @"报障设备";
//    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (void)resetCellFrameWithImages:(NSArray*)images cell:(UITableViewCell*)cell
{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    _currentEquipment.totalImageNameArray = arr;
    [self.tableView reloadData];
}

#pragma mark - YWSaveButtonCellDelegate
- (void)clickCancelButtonEvent:(UIButton *)button{
    if ([self.saveEquipmentArray containsObject:_currentEquipment]) {
        [self.saveEquipmentArray removeObject:_currentEquipment];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"cancelSaveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"operationFailed", nil)];
    }
}

- (void)clickSaveButtonEvent:(UIButton *)button{
    if ([YWCommonTool isContainsEmoji:_currentEquipment.psText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_currentEquipment.psText.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    __block BOOL isRequire = YES;
    //__block NSString *reasonable = nil;
    [_currentEquipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
        if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
            isRequire = NO;
            *fieldStop = YES;
        }
    }];
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    
    if (_currentEquipment) {
        if (![self.saveEquipmentArray containsObject:_currentEquipment]) {
            [self.saveEquipmentArray addObject:_currentEquipment];
        }
        [self.tableView reloadData];
        //下面这个刷新会导致调用cell的initWithStyle就重新构建了cell，导致图片消失
        //[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"saveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"noEquipmentToSelect", nil)];
    }
}

#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton*)sender{
    //报障
    NSArray *allEquipmentArray = nil;
    if (_qrcodeID) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrcodeID];
    }else if (_locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
//    YWEquipment *currentEqu = nil;
//    if (_currentEquipment && allEquipmentArray.count) {
//        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", _currentEquipment.equipmentId];
//        NSArray *array = [allEquipmentArray filteredArrayUsingPredicate:searchPredicate];
//        if (array.count>=1) {
//            currentEqu = array[0];}
//    }
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;// currentEqu ? currentEqu:(allEquipmentArray.count ? allEquipmentArray[0] : nil);
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrcodeID;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = (id<YWPostTroubleVCDelegate>)self.doEquipmentMissionVC;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}
//#pragma mark - YWPostTroubleVCDelegate
//- (void)passBackReportTrouble:(YWReportTroubleModel*)reportTrouble{
//    //报修记录
//    if (!_postTroubleRecordArray) {
//        _postTroubleRecordArray = [NSMutableArray array];
//    }
//    if (reportTrouble) {
//        [_postTroubleRecordArray addObject:reportTrouble];
//        [self.tableView reloadData];
//    }
//}

- (void)clickFinishButtonEvent:(UIButton*)sender{
    [self.view endEditing:YES];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"equipmentTypeId", _currentEquipment.equipmentTypeId];
    NSArray *currentSaveArray = [[self.saveEquipmentArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];

    if (currentSaveArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSaveTheWritings", nil)];
        return;
    }
    if (_currentEquipment.psText.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [currentSaveArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger equIdx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:equipment.psText]) {
            containEmoji = YES;
            *stop = YES;
        }
        [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
            if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
                isRequire = NO;
                *fieldStop = YES;
                *stop = YES;
            }
            if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
                reasonable = field.fieldName;
                //*fieldStop = YES;
            }
            if ([YWCommonTool isContainsEmoji:field.fieldValue]){
                containEmoji = YES;
                *stop = YES;
            }
        }];
    }];
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToFinish", nil)];
        
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
}

//- (MBProgressHUD*)HUD
//{
//    if (!_HUD) {
//        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
//        hud.labelFont = kHUDLabelFont;
//        hud.labelText = kTextSubmitTask;
//        hud.dimBackground = YES;
//        // hud.animationType = MBProgressHUDAnimationZoom;
//        _HUD = hud;
//        _HUD.tag = kMBProgressHUDTag;
//        [self.navigationController.view addSubview:hud];
//    }
//    return _HUD;
//}

#pragma mark - alert view
- (void)showTipsWhenFirstEnter{
    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstEnterDoMissionVC] boolValue];
    if (!notFirstEnter) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(KFirstEnterDoMissionVCTips, nil) preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"dontPromptAgain", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstEnterDoMissionVC];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
